package annotation.load;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Performance {

    public static void common() {
        long startTime = System.currentTimeMillis();
        Laby laby = new Laby();
        long endTime = System.currentTimeMillis();
        System.out.println("普通方法创建对象："+(endTime-startTime)+"ms");
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            laby.getName();
        }
        endTime = System.currentTimeMillis();
        System.out.println("普通方法执行方法："+(endTime-startTime)+"ms");
    }

    public static void reflect() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        long startTime = System.currentTimeMillis();
        Class classLaby = Class.forName("annotation.load.Laby");
        Laby laby = (Laby)classLaby.newInstance();
        long endTime = System.currentTimeMillis();
        System.out.println("反射方法创建对象："+(endTime-startTime)+"ms");
        startTime = System.currentTimeMillis();
        Method getName = classLaby.getMethod("getName");
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(laby);
        }
        endTime = System.currentTimeMillis();
        System.out.println("反射(需检查)方法："+(endTime-startTime)+"ms");
    }

    public static void reflectWithoutCheck() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        long startTime = System.currentTimeMillis();
        Class classLaby = Class.forName("annotation.load.Laby");
        Laby laby = (Laby)classLaby.newInstance();
        long endTime = System.currentTimeMillis();
        System.out.println("反射方法创建对象："+(endTime-startTime)+"ms");
        startTime = System.currentTimeMillis();
        Method getName = classLaby.getMethod("getName");
        getName.setAccessible(true);
        for (int i = 0; i < 1000000000; i++) {
            getName.invoke(laby);
        }
        endTime = System.currentTimeMillis();
        System.out.println("反射(不检查)方法："+(endTime-startTime)+"ms");
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        common();
        reflect();
        reflectWithoutCheck();
    }
}
